package com.zh.harmony.asynctask.slice;

import com.bumptech.glide.Glide;
import com.mingle.widget.ShapeLoadingDialog;
import com.zh.harmony.asynctask.AsyncTask;
import com.zh.harmony.asynctask.ResourceTable;
import com.zh.harmony.asynctask.util.HiLogUtil;
import com.zh.harmony.asynctask.util.HttpUtil;
import com.zh.harmony.asynctask.util.TextUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import okhttp3.*;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice {
    private Image vImage;
    private Button vLoadImg;
    private Button vNativeNetRequest;
    private Button vOkHttpNetRequest;

    private OkHttpClient mOkHttpClient;
    private ShapeLoadingDialog mLoadingDialog;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mOkHttpClient = new OkHttpClient.Builder().build();
        findView();
        bindView();
    }

    private void findView() {
        vImage = (Image) findComponentById(ResourceTable.Id_image);
        vLoadImg = (Button) findComponentById(ResourceTable.Id_load_img);
        vNativeNetRequest = (Button) findComponentById(ResourceTable.Id_native_net_request);
        vOkHttpNetRequest = (Button) findComponentById(ResourceTable.Id_okhttp_net_request);
    }

    private void bindView() {
        String imgUrl = "https://www.harmonyos.com/resource/image/release2/home/harmonyOS_logo.png";
        vLoadImg.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component v) {
                DownloadImageTask task = new DownloadImageTask(mOkHttpClient, new Callback<PixelMap>() {
                    @Override
                    public void onStart() {
                        vImage.setPixelMap(null);
                        showLoading();
                    }

                    @Override
                    public void onFinish(PixelMap pixelMap) {
                        hideLoading();
                        if (pixelMap != null) {
                            vImage.setPixelMap(pixelMap);
                        } else {
                            toast("下载失败");
                        }
                    }
                });
                task.execute(imgUrl);
            }
        });
        vLoadImg.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                Glide.with(getContext()).load(imgUrl).into(vImage);
            }
        });
        vNativeNetRequest.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                HttpURLConnectionNetRequestTask task = new HttpURLConnectionNetRequestTask(new Callback<String>() {
                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onFinish(String result) {
                        hideLoading();
                        if (!TextUtils.isEmpty(result)) {
                            HiLogUtil.info(result);
                            toast(result);
                        } else {
                            toast("网络请求失败");
                        }
                    }
                });
                task.execute("https://wanandroid.com/article/listproject/0/json");
            }
        });
        vOkHttpNetRequest.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                OkHttpNetRequestTask task = new OkHttpNetRequestTask(mOkHttpClient, new Callback<String>() {
                    @Override
                    public void onStart() {
                        showLoading();
                    }

                    @Override
                    public void onFinish(String result) {
                        hideLoading();
                        if (!TextUtils.isEmpty(result)) {
                            HiLogUtil.info(result);
                            toast(result);
                        } else {
                            toast("网络请求失败");
                        }
                    }
                });
                task.execute("https://wanandroid.com/article/listproject/0/json");
            }
        });
    }

    private static class DownloadImageTask extends AsyncTask<String, Void, PixelMap> {
        private final OkHttpClient mClient;
        private final Callback<PixelMap> mCallback;

        public DownloadImageTask(OkHttpClient client, Callback<PixelMap> callback) {
            mClient = client;
            mCallback = callback;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mCallback.onStart();
        }

        @Override
        protected PixelMap doInBackground(String... urls) {
            try {
                String url = urls[0];
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = mClient.newCall(request);
                Response response = call.execute();
                ResponseBody body = response.body();
                if (body == null) {
                    return null;
                }
                ImageSource imageSource = ImageSource.create(body.byteStream(), null);
                return imageSource.createPixelmap(null);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(PixelMap pixelMap) {
            super.onPostExecute(pixelMap);
            mCallback.onFinish(pixelMap);
        }
    }

    private static class HttpURLConnectionNetRequestTask extends AsyncTask<String, Void, String> {
        private final Callback<String> mCallback;

        public HttpURLConnectionNetRequestTask(Callback<String> callback) {
            this.mCallback = callback;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mCallback.onStart();
        }

        @Override
        protected String doInBackground(String... params) {
            return HttpUtil.httpGet(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            mCallback.onFinish(result);
        }
    }

    private static class OkHttpNetRequestTask extends AsyncTask<String, Void, String> {
        private final OkHttpClient mClient;
        private final Callback<String> mCallback;

        public OkHttpNetRequestTask(OkHttpClient client, Callback<String> callback) {
            this.mClient = client;
            this.mCallback = callback;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mCallback.onStart();
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                String url = params[0];
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = mClient.newCall(request);
                Response response = call.execute();
                ResponseBody body = response.body();
                if (body == null) {
                    return null;
                }
                return body.string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            mCallback.onFinish(result);
        }
    }

    /**
     * 回调接口
     */
    public interface Callback<T> {
        /**
         * 执行前回调
         */
        void onStart();

        /**
         * 执行后回调
         *
         * @param result 执行结果
         */
        void onFinish(T result);
    }

    @Override
    protected void onStop() {
        super.onStop();
        hideLoading();
        mLoadingDialog = null;
    }

    private void showLoading() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new ShapeLoadingDialog.Builder(this)
                    .loadText("加载中...")
                    //点击返回键时是否消失Dialog
                    .cancelable(true)
                    //点击Dialog外部时是否消失Dialog
                    .canceledOnTouchOutside(false)
                    .build();
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    private void hideLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.hide();
        }
    }

    private void toast(String msg) {
        new ToastDialog(getContext()
                .getApplicationContext())
                .setText(msg)
                .setAlignment(LayoutAlignment.CENTER)
                .show();
    }
}